from django.db import models


class Buyer(models.Model):
    """买家实体类"""
    name = models.CharField(max_length=64, unique=True)  # 用户名
    password = models.CharField(max_length=64)  # 密码
    email = models.EmailField(null=True)  # 邮箱
    phone = models.CharField(max_length=11, null=True)  # 电话
    address = models.CharField(max_length=32, null=True)  # 地址

    def __str__(self):
        return self.name

    class Meta:
        db_table = "buyer"


class Receiver(models.Model):
    """收件人实体类"""
    name = models.CharField(max_length=64)  # 姓名
    phone = models.CharField(max_length=64, null=True)  # 电话
    postcode = models.CharField(max_length=64, null=True)  # 邮编
    address = models.CharField(max_length=64, null=True)  # 地址
    isdefault = models.BooleanField(default=1, null=True)  # 是否为默认收获地址
    buyer = models.ForeignKey(to=Buyer, on_delete=models.CASCADE)  # 所属买家

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'reveiver'

class Cart(models.Model):
    """购物车"""
    goods = models.ForeignKey(to="bg.Goods", on_delete=models.CASCADE)  # 所属商品
    count = models.IntegerField()  # 数量
    buyer = models.ForeignKey(to=Buyer, on_delete=models.CASCADE)  # 所属用户

    def __str__(self):
        return self.buyer.name + '-' + self.goods.name

    class Meta:
        db_table = 'cart'

class Order(models.Model):
    """订单"""
    id = models.CharField(max_length=128, primary_key=True)  # 订单id
    buyer = models.ForeignKey(to=Buyer, on_delete=models.CASCADE)  # 用户，外键对象
    paymethod = models.IntegerField(default=3)  # 支付方式 1:货到付款 2:微信支付 3:支付宝 4:银联支付
    createtime = models.DateTimeField()  # 创建时间

    # 冗余,为了方便使用，允许部分冗余
    totalcount = models.IntegerField()  # 商品数量
    totalprice = models.FloatField()  # 商品总价

    freight = models.IntegerField()  # 订单运费
    status = models.IntegerField(default=1)  # 订单状态 1:待支付 2:待发货 3:待收货 4:待评价 5:已完成
    tradeno = models.CharField(max_length=64, null=True)  # 交易号
    tradetime = models.DateTimeField(null=True)  # 交易时间

    # 记录当时的收货信息
    name = models.CharField(max_length=64)  # 收货用户名
    postcode = models.CharField(max_length=64)  # 收货邮编
    phone = models.CharField(max_length=64)  # 收货电话
    address = models.CharField(max_length=64)  # 收货地址

    class Meta:
        db_table = 'order'


class OrderDetail(models.Model):
    """订单明细"""
    order = models.ForeignKey(to=Order, on_delete=models.CASCADE)#所属订单
    goods = models.ForeignKey(to="bg.Goods", on_delete=models.CASCADE)#所属商品
    count = models.IntegerField()#商品数量

    #记录当时购买的商品信息
    price = models.FloatField()#商品价格
    name = models.CharField(max_length=64)#商品名称
    picture = models.ImageField()#商品图片
    unite = models.CharField(max_length=64)#商品单位

    class Meta:
        db_table = 'orderdetail'